from django import forms
from .models import Student
from grades.models import Grades
from django.core.exceptions import ValidationError
import datetime

class StudentForm(forms.ModelForm):
    # 重写初始化方法
    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)
        self.fields.get('grade').queryset = Grades.objects.all().order_by('grade_number')
        
    def clean_student_name(self):
        student_name = self.cleaned_data.get('student_name')
        if len(student_name) < 2 or len(student_name) > 50:
            raise ValidationError('请填写正确的学生姓名')
        return student_name
    
    def clean_student_number(self):
        student_number = self.cleaned_data.get('student_number')
        if len(student_number) != 19:
            raise ValidationError('学籍号长度应为19位')
        return student_number
    
    def clean_birthday(self):
        birthday = self.cleaned_data.get('birthday')
        if not isinstance(birthday,datetime.date):
            raise ValidationError('生日日期格式不对，正确的格式例如2025-03-03')
        if birthday > datetime.date.today():
            raise ValidationError('生日应该在今天之后')
        return birthday
    
    def clean_contact_number(self):
        contact_number = self.cleaned_data.get('contact_number')
        if len(contact_number) != 11:
            raise ValidationError('手机号应为11位')
        return contact_number
    
    class Meta: # 创建元函数
        model = Student
        fields = ['student_name','student_number','grade','gender','birthday','contact_number','address']